package br.com.rapidrest.chain;

import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import br.com.rapidrest.exception.ChainException;

public class JspResponseCommand implements Command {

	private String extension = ".jsp";

	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();

		try {
			Class<?> beanClass = context.getBean().getClass();

			String webPackage = context.getWebPackage();
			String packagePath = beanClass.getPackage().getName();

			String dirPath = packagePath.replace(webPackage, "").replace(".",
					"/");

			String className = beanClass.getSimpleName();

			Method method = context.getMethod();

			StringBuilder jspName = new StringBuilder();
			jspName.append(dirPath).append("/").append(className);
			if (method != null
					&& !method.getName()
							.equals(BeanCommand.DEFAULT_INIT_METHOD)) {
				jspName.append(".").append(method.getName());
			}
			jspName.append(extension);

			HttpServletRequest request = context.getRequest();

			request.setAttribute("bean", context.getBean());
			request.setAttribute("value", context.getReturnedValue());

			RequestDispatcher requestDispatcher = request
					.getRequestDispatcher(jspName.toString());
			requestDispatcher.forward(request, context.getResponse());
		} catch (Exception e) {
			throw new ChainException(e);
		}
	}

	public String getExtension() {
		return extension;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

}
